'use strict';

var stepsApp = angular.module('stepsApp', ['ngRoute', 'fbdApp']);

// 验证模板名称是否被使用
stepsApp.factory('testName', function($http, $q) {
  return {
    test: function(url) {

      var deferred = $q.defer();

      $http.get(url).success(function(res) {
        deferred.resolve(res);
        // console.log(res);
      }).error(function(err) {
        deferred.reject(err);
      });
      return deferred.promise;
    }
  };
});



/**
 * ngroute
 *  路由配置
 *
 */
stepsApp.config(['$locationProvider', '$routeProvider', function(
  $locationProvider, $routeProvider) {


  // $locationProvider.html5Mode(true); //html5模式
  $routeProvider
    .when('/steps_1', {
      templateUrl: 'views/step/steps_1.html',
      controller: 'steps_1'
    })
    .when('/steps_2', {
      templateUrl: 'views/step/steps_2.html',

      controller: 'steps_2'

    })
    .when('/steps_3', {
      templateUrl: 'views/step/steps_3.html',
      controller: 'steps_3'
    })
    .when('/steps_4', {
      templateUrl: 'views/step/steps_4.html',
      controller: 'steps_4'
    })
    .otherwise({
      redirectTo: '/steps_1'
    });
}]);

/**
 * 控制器
 * steps_state[] :控制状态的数组
 * url           :下一步地址
 * changeA()     :改变状态的函数
 */

stepsApp.controller('steps', ['$scope', 'shareData', 'fbdService', '$filter',
  '$location',
  function($scope, shareData, fbdService, $filter, $location) {


    $scope.isOK = false; //next是否可用标志
    $scope.sonTemplate = false;
    // $scope.templatename = 'name';
    // $scope.isOK = new Boolean($scope.templatename);

    // $scope.$watch($scope.templatename,function (nval, oval) {
    //   alert(oval);
    // })

    // $scope.$watch('templatename', function (newval, oldval,scope) {
    //   if (newval) {
    //       shareData.tempName = newval;
    //       console.log('shareData.templatename:'+shareData.tempName);
    //       var promise = testName.test(url+newval);
    //       promise.then(function(res) {
    //         $scope.isOK = res;
    //         $scope.$emit('isOkName',res);
    //         console.log(res);
    //       }, function(err) {
    //         console.log(err);
    //       });
    //   }else{
    //     $scope.$emit('isOkName',false);
    //   }

    // });

    //获取是否模板名是否可用
    $scope.$on('isOkName', function(event, data) {
      // console.log('data===================================:' + data);
      if (data) {
        $scope.isOK = true;
      } else {
        $scope.isOK = false;
      }
      // alert(data);
    });

    $scope.$on('tempName', function(event, data) {
      $scope.tempName = data;
    });

    //获取是否上传了文件，进行下一步
    $scope.$on('isUploaded', function(event, data) {
      if (data) {
        $scope.isOK = true;
      }
      // alert(data);
    });

    //获取是否保存了，进行下一步
    $scope.$on('isSaved', function(event, data) {
      if (data) {
        $scope.isOK = true;
      }
      // alert(data);
    });



    //检测子模板
    $scope.$on('isSonTemplate', function(event, data) {
      // $location.path('/steps_1');
      // $location.replace();
      $scope.sonTemplate = data;
      $scope.isOK = false;
    });


    //每一步的状态
    $scope.steps_state = [{
      isBlue: true,
      isWordGray: false,
      isWordBlue: true,
      isWordBlack: false

    }, {
      isBlue: false,
      isWordGray: false,
      isWordBlue: false,
      isWordBlack: true
    }, {
      iisBlue: false,
      isWordGray: false,
      isWordBlue: false,
      isWordBlack: true

    }, {
      isBlue: false,
      isWordGray: false,
      isWordBlue: false,
      isWordBlack: true

    }];



    //点击next的方法
    $scope.changeA = function() {
      // alert($location.path());
      if ($location.path() == '/steps_1') {
        shareData.tempName.push($scope.tempName);
        console.log(shareData);
        // shareData.tempName = $scope.templatename;
        // console.log(shareData.tempName);
        $scope.steps_state[0].isBlue = false;
        $scope.steps_state[0].isWordGray = true;
        $scope.steps_state[0].isWordBlue = false;
        $scope.steps_state[0].isWordBlack = false;
        $scope.steps_state[1].isBlue = true;
        $scope.steps_state[1].isWordGray = false;
        $scope.steps_state[1].isWordBlue = true;
        $scope.steps_state[1].isWordBlack = false;

        // console.log('=:' + $location.absUrl());
        // console.log('=:' + $location.protocol());
        // console.log('=:' + $location.host());
        // console.log('=:' + $location.port());
        // console.log('=:' + $location.url());
        // console.log('=:' + $location.path());
        // alert('test'+$location.path())
        // $location服务为URL只读部分(absUrl, protocol, host, port)提供读方法，为可读写部分（url, path, search, hash）提供读写方法：
        //如果是子模板就直接跳过上传文件
        if ($scope.sonTemplate) {
          shareData.isMainRule = true;
          $scope.steps_state[1].isBlue = false;
          $scope.steps_state[1].isWordGray = true;
          $scope.steps_state[1].isWordBlue = false;
          $scope.steps_state[1].isWordBlack = false;
          $scope.steps_state[2].isBlue = true;
          $scope.steps_state[2].isWordGray = false;
          $scope.steps_state[2].isWordBlue = true;
          $scope.steps_state[2].isWordBlack = false;
          $location.path('/steps_3');
          $location.replace();
          $scope.isOK = false;
        } else {
          $location.path('/steps_2');
          $location.replace();
          $scope.isOK = false;
        }
        // $location.path('/steps_2');
        // $location.replace();
        // $scope.isOK = false;
      } else if ($location.path() == '/steps_2') {
        $scope.steps_state[1].isBlue = false;
        $scope.steps_state[1].isWordGray = true;
        $scope.steps_state[1].isWordBlue = false;
        $scope.steps_state[1].isWordBlack = false;
        $scope.steps_state[2].isBlue = true;
        $scope.steps_state[2].isWordGray = false;
        $scope.steps_state[2].isWordBlue = true;
        $scope.steps_state[2].isWordBlack = false;
        $location.path('/steps_3');
        $location.replace();
        $scope.isOK = false;

      } else if ($location.path() == '/steps_3') {

        //如果是子模板的话
        if ($scope.sonTemplate) {
          // alert('shareData.sonTemplate');
        }

        angular.element(document.querySelector('a')).text('save');
        // console.log(angular.element(document.querySelector('#button')).find(
        //   'a').text());
        $scope.steps_state[2].isBlue = false;
        $scope.steps_state[2].isWordGray = true;
        $scope.steps_state[2].isWordBlue = false;
        $scope.steps_state[2].isWordBlack = false;
        $scope.steps_state[3].isBlue = true;
        $scope.steps_state[3].isWordGray = false;
        $scope.steps_state[3].isWordBlue = true;
        $scope.steps_state[3].isWordBlack = false;
        $location.path('/steps_4');
        $location.replace();
        $scope.isOK = false;
      } else if ($location.path() == '/steps_4') {

        //如果是子模板的话
        if ($scope.sonTemplate) {
          // alert('shareData.sonTemplate');
        }

        $scope.steps_state[3].isBlue = false;
        $scope.steps_state[3].isWordGray = true;
        $scope.steps_state[3].isWordBlue = false;
        $scope.steps_state[3].isWordBlack = false;
        $scope.steps_state[0].isBlue = true;
        $scope.steps_state[0].isWordGray = true;
        $scope.steps_state[0].isWordBlue = true;
        $scope.steps_state[0].isWordBlack = false;
        $location.path('/steps_1');
        $location.replace();
        $scope.isOK = false;
      }

    }
  }
]);

stepsApp.controller('steps_1', ['$scope', 'shareData', 'fbdService', '$filter',
  '$location', 'testName',
  function($scope, shareData, fbdService, $filter, $location, testName) {
    $scope.isOK = ''; //next是否可用标志
    $scope.templatename = 'name';
    var url = 'http://localhost:3000/api/templates/check/';
    // 监控模板名称可用的时候存进shareData
    $scope.$watch('templatename', function(newval, oldval, scope) {
      if (newval) {
        // shareData.tempName = newval;
        // console.log('shareData.templatename:' + shareData.tempName);
        var promise = testName.test(url + newval);
        promise.then(function(res) {
          $scope.isOK = res;
          $scope.$emit('isOkName', res);
          $scope.$emit('tempName', newval);
          // console.log(res);
        }, function(err) {
          // console.log(err);
        });
      } else {
        $scope.isOK = false;
        $scope.$emit('isOkName', false);
      }

    });

  }
]);

stepsApp.controller('steps_2', ['$scope', 'shareData', function($scope,
  shareData) {
  // $scope.test = 'testinginginginginging2';
  $scope.$watch('fileName', function(v) {
    shareData.fileName = v;
    // console.log(shareData);
    shareData.textContent = {
      type: 'file',
      content: v
    };
    // console.log(shareData);
  });

  $scope.$watch('realFileName', function(v) {
    shareData.realFileName = v;
    // console.log(shareData);
  });
}]);
stepsApp.controller('steps_3', ['$scope', 'shareData', 'modalService',
  '$filter',
  function(
    $scope,
    shareData, modalService, $filter) {
    // modalService.showInfo($scope);

    // modalService.dismissModal($scope, 'cancel');
    $scope.realFileName = shareData.realFileName;
    $scope.fileName = shareData.fileName;
    // $scope.test = 'testinginginginginging3';

    $scope.$watch('savedRule', function(v) {
      if (v != undefined) {
        // modalService.closeModal($scope, v);

        // var struct = $filter('ruleFilter')(v);
        // console.log(struct);
        // console.log(v);
        // 是当前模板的主规则
        var struct = {
          rules: {},
          includes: [],
          require: [],
          before: [],
          after: []
        };
        if (shareData.isMainRule) {
          $scope.$watch('articleList', function(v) {
            if (v != undefined) {
              shareData.articleList.push(v);
            }
          });

          shareData.mainRules.push(v);

          shareData.layers.push(v.name);
          struct.includes.push(v.name);
          struct.require.push(v.name);
          shareData.currentTemplate.push(struct);
          var len = shareData.currentTemplate.length;
          shareData.rules[len - 1] = []; //开辟一个新数组
          var simplifiedRule = v;
          delete simplifiedRule.__v;
          delete simplifiedRule._id;
          shareData['currentTemplate'][len - 1]['rules'][v.name] =
            simplifiedRule;
          // shareData['currentTemplate']['rules'][v.name]['subset'] = {};

          shareData['currentTemplate'][len - 1]['rules'][v.name][
            'subset'
          ] = {
            rules: {},
            includes: [],
            require: [],
            before: [],
            after: []
          };
          shareData.currentLayer = shareData['currentTemplate'][len -
              1
            ]
            ['rules']
            [v.name]['subset'];
          shareData.isMainRule = false;
          console.log(shareData);

          // shareData.ruleLayer = shareData.rules.length;
          // shareData.rules[shareData.ruleLayer] = [];
        }
        // 当前模板的子规则
        else {
          // var len = shareData.currentTemplate.length;
          // var len = shareData.currentLayer.length;
          shareData['currentLayer']['rules'][v.name] = v;
          // shareData['currentTemplate']['rules'][v.name]['subset'] = {};
          // shareData.currentLayer.includes.push(v.name);
          // shareData.rules[len - 1].push(v);
          // console.log(shareData);
          // console.log(shareData.currentTemplate);
          // console.log(shareData.currentLayer);
        }
        // shareData.rules[shareData.ruleLayer].push(v);
        // console.log(shareData.currentTemplate);
        // console.log(shareData.rules);
      }
    });
    // $scope.articleList = shareData.articleList[shareData.articleList.length -
    //   1];

  }
]);

stepsApp.controller('steps_4', ['$scope', 'shareData', 'fbdService', '$filter',
  '$location', '$route',
  function($scope, shareData, fbdService, $filter, $location, $route) {
    var current = shareData.currentTemplate.length - 1;
    $scope.currentTemp = shareData.currentTemplate[current];
    // alert('aaa');
    // console.log(shareData.rules);
    // $scope.$watch('currentRule', function(v) {
    //   if (v != undefined) {
    //     shareData.rules[current].push(v);
    //   }
    // });
    $scope.$watch('rules', function(v) {
      console.log(v);
      shareData.rules[current] = v;
      console.log(shareData.rules[current]);
    }, true);
    // 添加完子模板后返回到母模板
    if (shareData.rules[current]) {
      console.log(shareData.rules[current]);
      $scope.rules = shareData.rules[current];
    } else {
      $scope.rules = [];
      // console.log('new');
    }

    // $scope.addSubTemplate = function() {
    //   shareData.isMainRule = true;
    // };

    $scope.testTemp = function() {

      $scope.postData = {};
      $scope.postData.text = shareData.textContent;
      $scope.postData.template = $filter('testTemplateData')($scope.rules,
        $scope.currentTemp);
      // console.log($scope.postData);
      // $scope.fileName = shareData.fileName;
      // $scope.testObj = {
      //   type: 'file',
      //   content: shareData.fileName
      // };


      // shareData.

      // $scope.fileName = shareData.realFileName;
      // $scope.postData = $filter('templateFilter')($scope.selectedRules,
      //   $scope.testObj);
      var promise = fbdService.test(
        'http://localhost:3000/api/templates/detect',
        $scope.postData);
      promise.then(function(res) {
        $scope.result = $filter('showTemplateFilter')(res);
        // $scope.result = res['main'][result];
        console.log($scope.result);


      }, function(err) {
        console.log(err);
      });
    };

    //保存模板的方法
    $scope.saveTemp = function() {
      $scope.addData = {
        name: shareData.tempName[current],
        content: $scope.postData.template
      };
      var promise = fbdService.save(
        'http://localhost:3000/api/templates/add',
        $scope.addData);
      promise.then(function(res) {

        console.log(res);
        // alert(res);

        // todo:
        // 1.去掉当前articleList和rules
        // 2.把mainRule pop并添加到上一层级的rules中
        // 3.改currentLayer
        // 4.去掉当前currentTemplate,并把当前的temp添加到上一层级的layer中
        if (current != 0) {
          console.log(current, 'current');

          shareData.rules[current - 1].push(shareData.mainRules[
            current]); //把当前主规则push到上层rules中展示
          shareData.currentLayer = shareData['currentTemplate'][
            current -
            1
          ]['rules'][shareData.layers[current - 1]]['subset']; //currentLayer变回上一层级的
          // shareData.currentLayer[current - 1].push(shareData.mainRules.pop());
          // shareData.currentLayer.pop();
          shareData['currentLayer']['rules'][shareData.layers[current]] =
            $scope.postData['template']['rules'][shareData.layers[
              current]]; //将处理过的数据赋给上一层模板
          shareData.currentTemplate.pop();
          shareData.mainRules.pop();
          shareData.articleList.pop();
          shareData.rules.pop();
          shareData.layers.pop();
          shareData.tempName.pop();
          console.log(shareData);

          // $location.path('/steps_4');
          // $location.replace();
          // window.location.reload();
          // window.location.href = window.location.href;

          $route.reload();
        }
        // window.location.href = '/index_2#/steps_4';
      }, function(err) {
        console.log(err);
      });
    };

  }
]);

stepsApp.controller('steps_5', ['$scope', 'shareData', 'modalService',
  '$filter', 'modalInfo', 'selected',
  function(
    $scope,
    shareData, modalService, $filter, modalInfo, selected) {
    // modalService.showInfo($scope);

    $scope.modalInfo = modalInfo;
    console.log(modalInfo);

    $scope.ruleData = selected;
    console.log(selected);

    //如果发生了变化，则存储

    modalService.dismissModal($scope, 'cancel');
    // $scope.realFileName = shareData.realFileName;
    // $scope.fileName = shareData.fileName;
    // $scope.test = 'testinginginginginging3';

    $scope.$watch('savedRule', function(v) {
      if (v != undefined) {
        modalService.closeModal($scope, v);
        shareData['currentLayer']['rules'][v.name] = v;
      }
    });
    $scope.articleList = shareData.articleList[shareData.articleList.length -
      1];

  }
]);
